package cn.exrick.xboot.modules.content.controller;


import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.redis.RedisTemplateHelper;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.config.custom.CustomPage;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.RestTemplateUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.config.custom.CustomPageUtils;
import cn.exrick.xboot.config.properties.RestTemplateProperties;
import cn.exrick.xboot.config.properties.XbootTokenProperties;
import cn.exrick.xboot.flow.entity.FlowUserinfo;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.content.entity.*;
import cn.exrick.xboot.modules.content.entity.HontVo.HontUserRolelevelQueryVo;
import cn.exrick.xboot.modules.content.entity.HontVo.HontUserRolelevelVo;
import cn.exrick.xboot.modules.content.service.*;
import cn.exrick.xboot.modules.content.service.mybatis.IHontUserRoleService;
import cn.exrick.xboot.modules.content.service.mybatis.IHontUserService;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static org.apache.poi.ss.usermodel.CellType.NUMERIC;
import static org.apache.poi.ss.usermodel.CellType.STRING;

/**
 * @author Exrick
 */
@Slf4j
@RestController
@Api(description = "前台用户管理接口")
@RequestMapping("/xboot/hontUser")
@CacheConfig(cacheNames = "hontUser")
@Transactional
public class HontUserController {

    @Autowired
    private XbootTokenProperties tokenProperties;
    @Autowired
    private HontUserService hontUserService;
    @Autowired
    private HontRoleService hontRoleService;
    @Autowired
    private HontUserRoleService hontUserRoleService;
    @Autowired
    private IHontUserRoleService iHontUserRoleService;
    @Autowired
    private HontPostService hontPostService;
    @Autowired
    private HontDepartmentService departmentService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateHelper redisTemplateHelper;
    @Autowired
    private HontDepartmentHeaderService hontDepartmentHeaderService;
    @Autowired
    private RestTemplateProperties restTemplateProperties;
    @Autowired
    private IHontUserService iHontUserService;
    @Autowired
    private HontUserPostService hontUserPostService;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SecurityUtil securityUtil;

    @RequestMapping(method = RequestMethod.GET, value = "/userInfo")
    public Result<HontUser> userInfo() {
        HontUser currUser = securityUtil.getCurrUser();
        return ResultUtil.data(currUser);
    }

    @RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取")
    public Result<Page<HontUser>> getByCondition(HontUser hontUser,
                                                 SearchVo searchVo,
                                                 PageVo pageVo) {


        Page<HontUser> page = hontUserService.findByCondition(hontUser, searchVo, PageUtil.initPage(pageVo));
        for (HontUser u : page.getContent()) {
            // 关联部门
            if (StrUtil.isNotBlank(u.getDepartmentId())) {
                HontDepartment department = departmentService.get(u.getDepartmentId());
                if (department != null) {
                    u.setDepartmentTitle(department.getTitle());
                }
            }
            //拥有权限
            List<HontDepartmentHeader> byHontUserId = hontDepartmentHeaderService.findByHontUserId(u.getId());
            if (byHontUserId.size() > 0) {
                List<String> hontDepartments = new ArrayList<>();
                for (int i = 0; i < byHontUserId.size(); i++) {
                    HontDepartment department = departmentService.get(byHontUserId.get(i).getHontDepartmentId());

                    hontDepartments.add(department.getTitle());
                }
                List<String> collect = hontDepartments.stream().distinct().collect(Collectors.toList());
                u.setDepartmentIds(collect);
            }

            //关联岗位
            List<HontUserPost> byHontUserPost = hontUserPostService.findByHontUserId(u.getId());
            if (byHontUserPost.size() > 0) {
                List<String> postIds = new ArrayList<>();
                for (int i = 0; i < byHontUserPost.size(); i++) {
                    HontPost hontPost = hontPostService.get(byHontUserPost.get(i).getHontPostId());
                    postIds.add(hontPost.getId());
                }
                u.setPostIds(postIds);
            }
            // 关联角色
            List<HontRole> list = iHontUserRoleService.findByUserId(u.getId());
            u.setRoles(list);
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    u.setRoleId(list.get(i).getId());
                }
            }

            //将
            // 清除持久上下文环境 避免后面语句导致持久化
            entityManager.clear();
            u.setPassWord(null);
        }
        return new ResultUtil<Page<HontUser>>().setData(page);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/selectAllList")
    public Result<Object> selectHistory(HontUser user, String roleId, CustomPage page) {
        CustomPage customPage = iHontUserService.selectAllListByHontUser(user, roleId, page);
        return ResultUtil.data(customPage);
    }

    @RequestMapping(value = "/fontResetPass", method = RequestMethod.POST)
    @ApiOperation(value = "重置密码")
    public Result<Object> fontResetPass(@RequestParam String id) {

        HontUser u = iHontUserService.getById(id);
        u.setPassWord(new BCryptPasswordEncoder().encode("hk" + u.getMobile().substring(u.getMobile().length() - 6)));
        iHontUserService.updateById(u);
        redisTemplate.delete("user::" + u.getUserName());
        return ResultUtil.success("操作成功");
    }

    @RequestMapping(value = "/getHontUserAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部用户数据")
    public Result<List<HontUser>> getByConditionAll() {

        List<HontUser> list = hontUserService.getAll();
        for (HontUser u : list) {
            // 关联部门
            if (StrUtil.isNotBlank(u.getDepartmentId())) {
                HontDepartment department = departmentService.get(u.getDepartmentId());
                if (department != null && department.getIsParent() == true) {
                    u.setDepartmentTitle(department.getTitle());
                    u.setDepartmentCopyTitle(null);
                } else if (department != null && department.getIsParent() == false) {
                    HontDepartment hontDepartment = departmentService.get(department.getParentId());
                    u.setDepartmentTitle(hontDepartment.getTitle());
                    u.setDepartmentCopyTitle(department.getTitle());
                }
            }
            //关联岗位
            List<HontUserPost> byHontUserPost = hontUserPostService.findByHontUserId(u.getId());
            if (byHontUserPost.size() > 0) {
                List<String> postIds = new ArrayList<>();
                for (int i = 0; i < byHontUserPost.size(); i++) {
                    HontPost hontPost = hontPostService.get(byHontUserPost.get(i).getHontPostId());
                    postIds.add(hontPost.getId());
                }
                u.setPostIds(postIds);
            }
            // 关联角色
            List<HontRole> roleList = iHontUserRoleService.findByUserId(u.getId());
            u.setRoles(roleList);
            // 清除持久上下文环境 避免后面语句导致持久化
            entityManager.clear();
            u.setPassWord(null);
        }
        return new ResultUtil<List<HontUser>>().setData(list);
    }

    @RequestMapping(value = "/admin/isForbidden", method = RequestMethod.POST)
    @ApiOperation(value = "后台开启和禁用用户")
    public Result<Object> isForbidden(@ApiParam("用户唯一id标识") String userId, String statu) throws JsonProcessingException, UnsupportedEncodingException {

        HontUser user = hontUserService.get(userId);
        String url = "http://localhost:8999/authentication/disable";
        ObjectMapper objectMapper = new ObjectMapper();

        //redisTemplate.delete(SecurityConstant.USER_TOKEN + user.getUsername());
        redisTemplate.opsForValue().set(SecurityConstant.USER_TOKEN + user.getUserName(), "isForbidden", tokenProperties.getSaveLoginTime(), TimeUnit.DAYS);
        if (user == null) {
            ResultUtil.error("通过userId获取用户失败");
        } else if (statu.equals("-1")) {
            user.setStatus(CommonConstant.USER_STATUS_LOCK);

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("userName", user.getUserName());
            String params = objectMapper.writeValueAsString(param);
            doPost(url, user.getUserName());

            hontUserService.update(user);
        } else {
            user.setStatus(CommonConstant.USER_STATUS_NORMAL);
            hontUserService.update(user);
        }
        //手动更新缓存
        redisTemplate.delete("user::" + user.getUserName());
        return ResultUtil.data(null);
    }

    @RequestMapping(value = "/admin/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加前台用户")
    public Result<HontUser> addHontUser(HontUser u, String roles, @RequestParam String[] postIds) throws Exception {
        return hontUserService.addHontUser(u, roles, postIds);
    }

    @RequestMapping(value = "/admin/ispass", method = RequestMethod.POST)
    @ApiOperation(value = "通过认证")
    public Result<Object> pass(@ApiParam(value = "用户唯一id") String userId, Integer approve) {
        HontUser user = hontUserService.get(userId);
        if (user == null) {
            ResultUtil.error("通过userId获取用户失败");
        } else if (approve == 1) {
            user.setApprove(CommonConstant.PASS);
            hontUserService.update(user);
        } else {
            user.setApprove(CommonConstant.OUT);
            hontUserService.update(user);
        }
        //手动更新缓存
        redisTemplate.delete("user::" + user.getUserName());
        return ResultUtil.data(null);
    }

    @RequestMapping(value = "/selectUserBuDepartmentId", method = RequestMethod.GET)
    @ApiOperation(value = "根据角色等级获取人员")
    public Result<Object> selectUserBuDepartmentId() {
        List<String> roleIdByhontUserId = iHontUserRoleService.findRoleIdByhontUserId();

        Set set = new HashSet();
        List<String> newList = new ArrayList();
        set.addAll(roleIdByhontUserId);
        newList.addAll(set);
        List<HontUser> users = new ArrayList<>();
        for (int i = 0; i < newList.size(); i++) {
            HontUser hontUser = hontUserService.get(newList.get(i));
            users.add(hontUser);
        }
        return ResultUtil.data(users);
    }
    // List<NameValuePair> params=new ArrayList<NameValuePair>();
  /*  public static String doPost(String url, String json) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonObject response = null;
        String result = "";
        try {
            StringEntity s = new StringEntity(json);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);

            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                result = EntityUtils.toString(res.getEntity());// 返回json格式：
                System.out.println(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }*/

    public static String doPost(String url, String json) throws UnsupportedEncodingException {
        //1.创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.创建HttpPost对象，设置URL地址
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("userName", json));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf8");
        httpPost.setEntity(formEntity);
        //使用httpClient发起响应获取repsonse
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            //4.解析响应，获取数据
            //判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return "22";
    }

    @RequestMapping(value = "/admin/customeEdit", method = RequestMethod.POST)
    @ApiOperation(value = "管理员修改资料", notes = "需要通过id获取原用户信息 需要username更新缓存")
    @CacheEvict(key = "#u.nickName")
    public Result<Object> customeEdit(HontUser u, String roles, @RequestParam String[] postIds) throws Exception {
        HontUser old = hontUserService.findById(u.getId());
        //若修改了用户名
        if (u.getType() == 1) {
            HontUser byUserName = hontUserService.findByUserName(u.getUserName());
            if (byUserName != null && !byUserName.getId().equals(u.getId())) {
                return ResultUtil.error("该账户已被注册");
            }

        }
        if (u.getType() == 0) {
            if (StrUtil.isBlank(u.getMobile())) {
                return ResultUtil.error("缺少必需表单字段");
            }
            // 若修改了手机和邮箱判断是否唯一
            if (old.getMobile() != null && !old.getMobile().equals(u.getMobile()) && hontUserService.findByMobile(u.getMobile()) != null) {
                return ResultUtil.error("该手机号已绑定其他账户");
            }
            u.setUserName(u.getMobile());
        }
        if (!old.getNickName().equals(u.getNickName())) {
            //若修改用户名删除原用户名缓存
            redisTemplate.delete("hontUser::" + old.getNickName());
            //判断新用户名是否存在
            if (hontUserService.findByNickName(u.getNickName()) != null) {
                return ResultUtil.error("该用户名已被存在");
            }
        }
        old.setPostId(u.getPostId());
        old.setNickName(u.getNickName());
        old.setMobile(u.getMobile());
        old.setUserName(u.getUserName());
        old.setDepartmentId(u.getDepartmentId());
        old.setDepartmentCopyId(u.getDepartmentId());
        HontUser user = hontUserService.update(old);
        if (user == null) {
            return ResultUtil.error("修改失败");
        }
        //删除岗位
        hontUserPostService.deleteByHontUserId(u.getId());
        if (postIds.length > 0) {
            for (int i = 0; i < postIds.length; i++) {
                HontUserPost hontUserPost = new HontUserPost();
                hontUserPost.setHontPostId(postIds[i]);
                hontUserPost.setHontUserId(u.getId());
                hontUserPostService.save(hontUserPost);
            }
        }
        //删除该用户角色
        hontUserRoleService.deleteByHontUserId(u.getId());
        HontRole hontRole = hontRoleService.get(roles);
        if (hontRole != null && hontRole.getName().equals("员工")) {
            hontDepartmentHeaderService.deleteByHontUserId(u.getId());
        }
        if (roles != null && !roles.equals("")) {
            if (hontRoleService.get(roles) == null) {
                return ResultUtil.error("该角色不存在");
            }
            //新角色
            HontUserRole ur = new HontUserRole();
            ur.setHontRoleId(roles);
            ur.setHontUserId(u.getId());
            hontUserRoleService.save(ur);
        } else {
            List<HontRole> byDefaultRole = hontRoleService.findByDefaultRole(true);
            for (int i = 0; i < byDefaultRole.size(); i++) {
                HontUserRole ur = new HontUserRole();
                ur.setHontRoleId(byDefaultRole.get(i).getId());
                ur.setHontUserId(u.getId());
                hontUserRoleService.save(ur);
            }
        }
        //手动删除缓存
        redisTemplate.delete("hontUserRole::" + u.getId());
        redisTemplate.delete("hontUserRole::depIds:" + u.getId());
        redisTemplate.delete("hontUserPermission::" + u.getId());
        redisTemplate.delete("hontPermission::hontUserMenuList:" + u.getId());
        return ResultUtil.success("修改成功");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    public Result<Object> delAllByIds(@PathVariable String[] ids) throws Exception {

        for (String id : ids) {
            HontUser u = hontUserService.get(id);
            //删除缓存
            redisTemplate.delete("hontUser::" + u.getUserName());
            redisTemplate.delete("hontUserRole::" + u.getId());
            redisTemplate.delete("hontUserRole::depIds:" + u.getId());
            redisTemplate.delete("hontPermission::hontUserMenuList:" + u.getId());
            Set<String> keys = redisTemplateHelper.keys("hontDepartment::*");
            redisTemplate.delete(keys);
            hontUserService.delete(id);
            //删除关联角色
            hontUserRoleService.deleteByHontUserId(id);
            //删除关联部门负责人
            hontDepartmentHeaderService.deleteByHontUserId(id);
           /* String url = restTemplateProperties.getUrl();
            String restUrl = url +  "/rest/dataSynchronization/deleteUser";
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("userId",u.getId());
            Result<Object> objectResult = RestTemplateUtil.sendPostRequest(restUrl, params);
            if (objectResult.getCode() != 200){
                throw new Exception("远程调用失败");
            }*/
        }

        return ResultUtil.success("批量通过id删除数据成功");
    }

    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传")
    public Result<Object> upload(MultipartFile file, HttpServletRequest request) throws Exception {
        InputStream inputStream = file.getInputStream();

        XSSFWorkbook wookbook = new XSSFWorkbook(inputStream);

        XSSFSheet sheet = wookbook.getSheet("Sheet1");

        //获取到Excel文件中的所有行数

        int rows = sheet.getPhysicalNumberOfRows();

        //遍历行

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        for (int i = 1; i < rows; i++) {
            // 读取左上端单元格

            XSSFRow row = sheet.getRow(i);

            // 行不为空

            if (row != null) {
                Map<String, String> map = new HashMap<String, String>();

                //获取到Excel文件中的所有的列

                int cells = row.getPhysicalNumberOfCells();

                //昵称

                XSSFCell name = row.getCell(1);

                String nickName = getValue(name);

                //手机号

                XSSFCell mobile = row.getCell(5);

                String mobileP = getValue(mobile);

                //角色

                XSSFCell ageCell = row.getCell(4);

                String roles = getValue(ageCell);

                //部门
                XSSFCell departId = row.getCell(2);

                String departmentId = getValue(departId);

                //岗位
                XSSFCell post = row.getCell(3);

                String postId = getValue(post);

                //用户类型：1，手机号2，账号
                XSSFCell userType = row.getCell(6);

                String userTypes = getValue(userType);


                map.put("nickName", nickName);

                map.put("mobile", mobileP);

                map.put("roles", roles);

                map.put("departmentId", departmentId);

                map.put("postId", postId);

                map.put("userType", userTypes);

                list.add(map);

            }

        }

        System.out.println("list = " + JSON.toJSONString(list));
        //用户

        List<String> userNames = list.stream().map(t -> t.get("mobile")).collect(Collectors.toList());
        List<HontUser> allByUserName = iHontUserService.selectAllByUserName(userNames);
        if (allByUserName.size() > 0) {
            String join = StringUtils.join(allByUserName, ",");
            return ResultUtil.error(join + ",以上用户均已存在,请修改后上传");
        }
        //岗位
        List<String> postIds = list.stream().map(s -> s.get("postId")).collect(Collectors.toList());
        List<String> postNulls = new ArrayList<>();
        for (int i = 0; i < postIds.size(); i++) {
            if (StringUtils.isNotBlank(postIds.get(i))) {
                List<String> postId = Arrays.asList(postIds.get(i).split(","));
                for (int i1 = 0; i1 < postId.size(); i1++) {
                    HontPost allByTitle = hontPostService.findByTitle(postId.get(i1));
                    if (allByTitle == null) {
                        postNulls.add(postId.get(i1));
                    }
                }
            }
        }
        if (postNulls.size() > 0) {
            String join = StringUtils.join(postNulls, ",");
            return ResultUtil.error(join + ",以上岗位不存在,请修改后上传");
        }
        //部门
        List<String> departmentIds = list.stream().map(s -> s.get("departmentId")).collect(Collectors.toList());
        List<String> departmentIdNulls = new ArrayList<>();
        for (int i = 0; i < departmentIds.size(); i++) {
            HontDepartment byTitle = departmentService.findByTitle(departmentIds.get(i));
            if (byTitle == null) {
                departmentIdNulls.add(departmentIds.get(i));
            }
        }
        if (departmentIdNulls.size() > 0) {
            String join = StringUtils.join(departmentIdNulls, ",");
            return ResultUtil.error(join + ",以上部门不存在,请修改后上传");
        }
        //角色
        List<String> rolesIds = list.stream().map(s -> s.get("roles")).collect(Collectors.toList());
        List<String> rolesIdsNulls = new ArrayList<>();
        for (int i = 0; i < rolesIds.size(); i++) {
            HontRole roles = hontRoleService.findByName(rolesIds.get(i));
            if (roles == null) {
                rolesIdsNulls.add(rolesIds.get(i));
            }
        }
        if (rolesIdsNulls.size() > 0) {
            String join = StringUtils.join(rolesIdsNulls, ",");
            return ResultUtil.error(join + ",以上角色不存在,请修改后上传");
        }

        for (int i = 0; i < list.size(); i++) {
            HontUser user = new HontUser();

            user.setNickName(list.get(i).get("nickName"));
            String mobile = list.get(i).get("mobile");
            String userType = list.get(i).get("userType");
            if (userType.equals("0")) {
                user.setMobile(mobile);
                user.setUserName(mobile);
                String s = "hk" + mobile.substring(mobile.length() - 6, mobile.length());
                String password = new BCryptPasswordEncoder().encode(s);
                user.setPassWord(password);
                user.setType(Integer.parseInt(userType));
            } else if (userType.equals("1")) {
                user.setUserName(mobile);
                String s = "hk123456";
                String password = new BCryptPasswordEncoder().encode(s);
                user.setPassWord(password);
                user.setType(Integer.parseInt(userType));
            }
            //部门
            HontDepartment departmentId = departmentService.findByTitle(list.get(i).get("departmentId"));
            user.setDepartmentId(departmentId.getId());
            user.setCreateTime(LocalDateTime.now());
            user.setIsBackstage(0);
            //岗位
            //角色
            HontRole roles = hontRoleService.findByName(list.get(i).get("roles"));

            List<String> postTitles = Arrays.asList(list.get(i).get("postId").split(","));
            String[] postIdByTitle = new String[postTitles.size()];
            for (int i1 = 0; i1 < postTitles.size(); i1++) {
                HontPost allByTitle = hontPostService.findByTitle(postTitles.get(i1));
                postIdByTitle[i1] = allByTitle.getId();
            }
            hontUserService.addHontUser(user, roles.getId(), postIdByTitle);
        }
        return ResultUtil.success("上传成功");
    }

    private String getValue(XSSFCell xSSFCell) {
        if (null == xSSFCell) {
            return "";

        }

        if (xSSFCell.getCellType() == NUMERIC) {

            // 返回数值类型的值
            xSSFCell.setCellType(STRING);

            return String.valueOf(xSSFCell.getStringCellValue());

        } else {

            // 返回字符串类型的值

            return String.valueOf(xSSFCell.getStringCellValue());

        }

    }

    @ResponseBody
    @GetMapping("/getUser")
    public Result<Object> getHontUserList(HontUserRolelevelQueryVo hontUserRolelevelQueryVo) {
        List<HontUserRolelevelVo> hontUserRolelevelVos =
                iHontUserService.getHontUserAndRoleAndLevel(hontUserRolelevelQueryVo);
        return ResultUtil.data(hontUserRolelevelVos);
    }

    /**
     * 一键同步所有用户岗位
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/syncUserPost")
    public Result<Object> syncUserPost() {
        List<HontUser> list = hontUserService.getAll();
        List<HontUser> allUser = list.stream().filter(u -> null != u.getPostId()).collect(Collectors.toList());

        List<HontUserPost> userPosts = hontUserPostService.getAll();
        List<String> postUserId = userPosts.stream().map(HontUserPost::getHontUserId).collect(Collectors.toList());
        List<HontUser> collect = allUser.stream().filter(item -> !postUserId.contains(item.getId())).collect(Collectors.toList());
        if (collect.size() > 0) {
            int i = hontUserPostService.batchInsert(collect);
            return ResultUtil.data(i);
        } else {
            return ResultUtil.error("暂无需要同步的数据");
        }

    }

    /**
     * 功能描述:
     *
     * @return:
     * @Author: 杨春科
     * @Date: 27/10/2022 上午10:59
     * @Description //TODO
     */
    @ResponseBody
    @PostMapping("/authorizationBackground")
    public Result<Object> authorizationBackground(String hontUserId, Integer isBackstage) {
        return iHontUserService.authorizationBackground(hontUserId, isBackstage);


    }
}
